package com.example.playbox

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.example.playbox.bean.Student
import com.example.playbox.utils.StudentDbHelper

class MyIFActivity : AppCompatActivity() {

    private lateinit var tvStuName: TextView
    private lateinit var tvStuMajor: TextView
    private lateinit var tvStuPhone: TextView
    private lateinit var tvStuQq: TextView
    private lateinit var tvStuAddress: TextView
    private lateinit var etUserNumber: EditText

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my_ifactivity)

        val btnBack: Button = findViewById(R.id.btn_back)
        btnBack.setOnClickListener { finish() }

        etUserNumber = findViewById(R.id.tv_stu_number)
        etUserNumber.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                updateStudentInfo(s.toString())
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
        })

        tvStuName = findViewById(R.id.tv_stu_name)
        tvStuMajor = findViewById(R.id.tv_stu_major)
        tvStuPhone = findViewById(R.id.tv_stu_phone)
        tvStuQq = findViewById(R.id.tv_stu_qq)
        tvStuAddress = findViewById(R.id.tv_stu_address)

        val btnModifyInfo: Button = findViewById(R.id.btn_modify_info)
        btnModifyInfo.setOnClickListener {
            val intent = Intent(applicationContext, UpdateIFActivity::class.java)
            val bundle = Bundle()
            bundle.putString("stu_number2", etUserNumber.text.toString())
            intent.putExtras(bundle)
            startActivity(intent)
        }
    }

    private fun updateStudentInfo(stuNumber: String) {
        val dbHelper = StudentDbHelper(applicationContext, StudentDbHelper.DB_NAME, null, 1)
        val students = dbHelper.readStudents(stuNumber)

        if (students != null) {
            for (student in students) {
                tvStuName.text = student.stuName
                tvStuMajor.text = student.stuMajor
                tvStuPhone.text = student.stuPhone
                tvStuQq.text = student.stuQq
                tvStuAddress.text = student.stuAddress
            }
        } else {
            tvStuName.text = "暂未填写"
            tvStuMajor.text = "暂未填写"
            tvStuPhone.text = "暂未填写"
            tvStuQq.text = "暂未填写"
            tvStuAddress.text = "暂未填写"
        }
    }
}